import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_fronter_service/model/OrderDetail.dart';
import 'package:flutter_fronter_service/model/order_entity.dart';
import 'package:flutter_fronter_service/page/tap.dart';
import 'package:flutter_fronter_service/tools/commons.dart';
import 'package:get/get.dart';


import '../api/orderApi.dart';
import '../controller/AllControllerBinding.dart';
import '../controller/userController.dart';
import '../model/address_entity.dart';
import '../model/properties_entity.dart';
import '../model/sku_entity.dart';
import '../tools/constant.dart';

class OrderDetailsPage extends StatefulWidget {
  const OrderDetailsPage({super.key});

  @override
  State<OrderDetailsPage> createState() => _OrderDetailsPageState();
}

class _OrderDetailsPageState extends State<OrderDetailsPage> {

  late OrderEntity orderEntity;
  late double totalPrice = 0;
  bool isLoading =  true;
  //支付方式
  String selectedPaymentMethod = '';

  //弹窗效果
  void showPaymentSheet() {
    //支付弹窗
    showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return PaymentSheet(
          totalPrice: totalPrice,
          onPaymentMethodSelected: (method) {
            setState(() {
              selectedPaymentMethod = method;
            });
          },
        );
      },
    ).then((value) => value == true?processPayment():null);
  }

  //支付请求
  Future<void> processPayment() async {
    var res = await updateOrderStateApi({"id":orderEntity.id,"state":ORDER_STATE_PAID});
    orderEntity.orderState = res["data"]["orderState"];
    CommonUtils.showBotToast("支付成功");
    setState(() {
    });
  }

  Future<void> _loadOrderDetails() async {
    List<OrderDetail> orderDetails = [];
    //获取订单id
    var res = await getOrderByIdApi(Get.arguments["id"]);
    //解析order
    orderEntity = OrderEntity.fromJson(res["data"]);
    //解析地址
    orderEntity.addressEntity = AddressEntity.fromJson(res["data"]["deliveryAddress"]);
    //解析商品
    for(int i=0;i<res["data"]["detailsVos"].length;i++){
      //规格列表
      late RxList<PropertiesEntity> itemSpecList = <PropertiesEntity>[].obs;
      late String goodsSpec = "";
      //属性解析
      res["data"]["detailsVos"][i]["skuItemVo"]["itemSpec"].forEach((item)=>itemSpecList.add(PropertiesEntity.fromJson(item)));
      SkuEntity sku = SkuEntity.fromJson(res["data"]["detailsVos"][i]["skuItemVo"]);
      sku.goodsPrice =  res["data"]["detailsVos"][i]["skuItemVo"]["goodsPrice"];
      sku.goodsName = res["data"]["detailsVos"][i]["skuItemVo"]["goodsName"];
      
      sku.itemSpec = itemSpecList;

      itemSpecList.forEach((element) {
        goodsSpec = goodsSpec +' '+ element.value;
      });

      //订单细则
      OrderDetail orderDetail = OrderDetail(res["data"]["detailsVos"][i]["quantity"],
        sku,
        goodsSpec,
      );
      //计算价格
      totalPrice = (sku.goodsPrice * orderDetail.quantity) + totalPrice;

      orderDetails.add(orderDetail);
    }
    //商品赋值
    orderEntity.orderDetails = orderDetails;

    setState(() {
      isLoading =  false;
    });

  }


  @override
  void initState() {
    super.initState();
    _loadOrderDetails();
  }

  @override
  Widget build(BuildContext context) {
    double shippingFee = 5.0;

    return Scaffold(
      appBar: AppBar(
        title: Text('订单详情'),
        centerTitle: true,
      ),
      body: isLoading ? Center(child: CircularProgressIndicator()) : SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 收货地址
             Card(
              margin: EdgeInsets.only(bottom: 16),
              child: ListTile(
                title: Text(orderEntity.addressEntity.contactName),
                subtitle: Text(
                    '${orderEntity.addressEntity.province}${orderEntity.addressEntity.city}${orderEntity.addressEntity.district}${orderEntity.addressEntity.address}'
                        '\n${orderEntity.addressEntity.contactName}'),
                leading: Icon(Icons.location_on),
              ),
            ),
            // 商品详情
            Card(
              margin: EdgeInsets.only(bottom: 16),
              child: Column(
                children: [
                  ...orderEntity.orderDetails.map((orderDetail) => OrderItemCard(orderDetail: orderDetail)),
                  const Divider(),
                  orderEntity.orderState == ORDER_STATE_PAID?Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      TextButton.icon(
                        onPressed: () {},
                        icon: Icon(Icons.shopping_cart),
                        label: Text('再次购买'),
                      ),
                      TextButton.icon(
                        onPressed: () {},
                        icon: Icon(Icons.rate_review),
                        label: Text('评价'),
                      ),
                    ],
                  ):Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      TextButton.icon(
                        onPressed: () {},
                        icon: Icon(Icons.access_time),
                        label: Text('申请售后 '),
                      )
                    ],
                  )
                ],
              ),
            ),
            // 订单信息
            Card(
              margin: EdgeInsets.only(bottom: 16),
              child: Column(
                children: [
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('订单编号'),
                        Row(
                          children: [
                            Text(orderEntity.id.toString()),
                            IconButton(
                              icon: Icon(Icons.copy,size: 10,),
                              onPressed: () {
                                Clipboard.setData(
                                    ClipboardData(text: orderEntity.id.toString()));
                                ScaffoldMessenger.of(context)
                                    .showSnackBar(SnackBar(
                                      content: Text('订单编号已复制'),
                                ));
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('备注'),
                        Text('无'),
                      ],
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('配送时间'),
                        Text('周末'),
                      ],
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('下单时间'),
                        Text(orderEntity.createTime.toString()),
                      ],
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('运费'),
                        Text('¥$shippingFee'),
                      ],
                    ),
                  ),
                  Divider(),
                  ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('需支付'),
                        Text('¥${totalPrice + shippingFee}'),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: EdgeInsets.all(16),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end  ,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            orderEntity.orderState == ORDER_STATE_PAID?Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                ElevatedButton(
                  onPressed: () {
                    //返回根目录
                    // Get.offAndToNamed("/orderList");
                    // Get.toNamed("/");
                    Get.to(()=> Taps(), binding: AllControllerBinding());
                  },
                  child: Text('返回'),
                ),
                ElevatedButton(
                  onPressed: () {
                    // 取消订单逻辑
                  },
                  child: Text('删除订单'),
                ),
              ],
            ):Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    // 取消订单逻辑
                  },
                  child: Text('取消订单'),
                ),
                SizedBox(width: 8),
                ElevatedButton(
                  onPressed: () {
                    Get.offAndToNamed("/");
                  },
                  child: Text('稍后支付'),
                ),
                SizedBox(width: 8),
                ElevatedButton(
                  onPressed: ()  {
                    showPaymentSheet();
                  },
                  child: Text('去支付'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

//订单详情卡片
class OrderItemCard extends StatelessWidget {
  final OrderDetail orderDetail;

  const OrderItemCard({Key? key, required this.orderDetail}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Image.network(
        orderDetail.skuEntity.itemImg,
        width: 50,
        height: 50,
        fit: BoxFit.cover,
      ),
      title: Text(orderDetail.skuEntity.goodsName),
      subtitle: Text('规格: ${orderDetail.spec}\n数量: ${orderDetail.quantity}'),
      trailing: Text('￥${orderDetail.skuEntity.goodsPrice}'),
    );
  }
}

//支付弹窗
class PaymentSheet extends StatefulWidget {
  final double totalPrice;
  final Function(String) onPaymentMethodSelected;

  PaymentSheet({required this.onPaymentMethodSelected, required this.totalPrice});

  @override
  _PaymentSheetState createState() => _PaymentSheetState();
}

class _PaymentSheetState extends State<PaymentSheet> {
  String selectedMethod = '';
  // UserController userController = Get.find<UserController>();

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.7,
      padding: EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 支付金额
          Container(
            height: 100,
            //内容居中
            alignment: Alignment.center,
            child: Text(
              '支付金额：¥${widget.totalPrice}',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
          ),
          Divider(),
          // 账号
          ListTile(
            leading: Icon(Icons.account_circle),
            title: Text('账号'),
            subtitle: Text("张三"),
          ),
          Divider(),
          // 付款方式
          Text(
            '选择付款方式',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          RadioListTile<String>(
            title: Text('微信支付'),
            value: '微信支付',
            groupValue: selectedMethod,
            onChanged: (value) {
              setState(() {
                print(value);
                selectedMethod = value!;
                widget.onPaymentMethodSelected(selectedMethod);
              });
            },
          ),
          RadioListTile<String>(
            title: Text('支付宝支付'),
            value: '支付宝支付',
            groupValue: selectedMethod,
            onChanged: (value) {
              setState(() {
                selectedMethod = value!;
                widget.onPaymentMethodSelected(selectedMethod);
              });
            },
          ),
          RadioListTile<String>(
            title: Text('其他支付方式'),
            value: '其他支付方式',
            groupValue: selectedMethod,
            onChanged: (value) {
              setState(() {
                selectedMethod = value!;
                widget.onPaymentMethodSelected(selectedMethod);
              });
            },
          ),
          Spacer(),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context, true);
            },
            child: Center(child: Text('立即支付')),
          ),
        ],
      ),
    );
  }
}